package top.byfree.jbyan.saber.service

import org.ktorm.dsl.and
import org.ktorm.dsl.eq
import org.ktorm.dsl.limit
import org.ktorm.dsl.map
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import top.byfree.jbyan.saber.bean.IS_DELETE_NO
import top.byfree.jbyan.saber.bean.Users
import top.byfree.jbyan.saber.bean.dto.FilterUserDto
import top.byfree.jbyan.saber.bean.dto.PageDto
import top.byfree.jbyan.saber.bean.dto.RegisterDto
import top.byfree.jbyan.saber.bean.dto.UserDto
import top.byfree.jbyan.saber.bean.vo.UserVo
import top.byfree.jbyan.saber.common.AddGroup
import top.byfree.jbyan.saber.common.IdWorker
import top.byfree.jbyan.saber.common.excel.toExcel
import top.byfree.jbyan.saber.dao.UserDao
import top.byfree.jbyan.saber.dao.UserRoleDao

/**
 * 用户业务逻辑层
 *
 * @author jbyan
 * @since 21/3/2024
 */
@Service
open class UserService(
    @Autowired open val userDao: UserDao,
    @Autowired open val userRoleDao: UserRoleDao,
    @Autowired open val idWorker: IdWorker,
) {

    /* 获取指定用户详细信息 */
    fun getOne(userId: String) = userDao.findOne { it.userId eq userId }?.toVo()

    /* 获取用户拥有的角色 */
    fun getRoleList(userId: String) = userDao.findRoles(userId).map { it.toVo() }

    /* 获取用户拥有的权限 */
    fun getPermList(userId: String) = userDao.findPerms(userId).map { it.toVo() }

    /* 根据用户名称检索用户 */
    fun byUsername(username: String) = userDao.findOne { (it.username eq username) and (it.isDelete eq IS_DELETE_NO) }

    /* 根据邮箱检索用户 */
    fun byEmail(email: String) = userDao.findOne { it.email eq email and (it.isDelete eq IS_DELETE_NO) }

    /* 新增用户 */
    fun add(registerDto: RegisterDto) = userDao.add(registerDto.toUser(idWorker.nextId())) > 0

    /* 新增通过UserDto */
    fun add(userDto: UserDto) = userDao.add(userDto.toUser(idWorker.nextId(), AddGroup::class.java)) > 0

    /* 修改当前用户信息 */
    fun updateCurrent(userDto: UserDto) = userDao.update(userDto.toUser()) > 0

    /* 修改指定用户信息 */
    fun update(userId: String, userDto: UserDto) = userDao.update(userDto.toUser(userId)) > 0

    /* 删除指定用户，逻辑删除 */
    fun delete(userList: MutableList<String>) = userDao.logicDelete(userList)

    /* 分页条件查询用户列表 */
    fun page(size: Int = 10, current: Int = 1, filterUserDto: FilterUserDto): PageDto<UserVo> {
        // 通过 size 和 current 计算 offset 值
        val offset = size * (current - 1)
        val query = userDao.filter(filterUserDto)
            .limit(offset, size)
        return PageDto(query.map(Users::createEntity).map { it.toVo() }, query.totalRecordsInAllPages, current, size)
    }

    /* 修改用户角色关联 */
    @Transactional
    open fun editRole(userId: String, roles: MutableList<String>) {
        // 1. 删除用户全部角色关联
        userRoleDao.deleteIf { it.userId eq userId }
        // 2. 为用户新增角色关联信息
        userRoleDao.batchAdd {
            roles.forEach { roleId ->
                item {
                    set(it.userId, userId)
                    set(it.roleId, roleId)
                }
            }
        }
    }

    /* 生成要导出的excel */
    fun excel(size: Int = 1000, current: Int, filterUserDto: FilterUserDto) =
        toExcel(page(size, current, filterUserDto).modelList, filterUserDto.exportCol)


}